package com.mediacloud.app.newsmodule.activity;

import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;

import com.eventTrack.CDPTrackReportManager;
import com.eventTrack.DataCollectRequestButtonClickExpansion;
import com.eventTrack.TXReportManager;
import com.mediacloud.app.model.CommentCommitPushEvent;
import com.mediacloud.app.model.activity.BaseBackActivity;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.newsmodule.datacollect.IButtonClickDataCollect;
import com.mediacloud.app.newsmodule.datacollect.IButtonClickLike;
import com.mediacloud.app.newsmodule.datacollect.IPageEventDataCollect;
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.ShareGridClickUtil;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.user.model.UserInfo;
import com.utils.read.AudioFloatManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.security.SecureRandom;
import java.text.DecimalFormat;

/**
 * 使用 ArticleItem统一处理页面相关的数据采集
 * 注意因为页面开启事件具有一定的特殊性，需要在数据加载成功后{@link #articleItem}初始化后在采集，
 * 否则数据会为肯定为空。数据初始化后调用{@link #onPageStart()}
 * <p>
 * 1.对于点赞按键的采集：在点赞的View初始化完成的时候，对于点赞事件的采集如果是使用的{@link com.mediacloud.app.assembly.views.LikeBadgeView}
 * 可以直接调用{@link com.mediacloud.app.assembly.views.LikeBadgeView#setmButtonClickLike(IButtonClickLike)}方法进行数据采集设置
 * 对于其他的点赞点击事件，需要自己在onClickListener中处理
 * 2.对于评论的采集：在当前类已经处理了CommentPopupWindow，没有特殊情况的话子类不用在进行处理
 * 3.对于关注的采集，在对应的事件按钮进行处理
 * 4.对于转发的采集，已经集成在{@link  ShareGridClickUtil#ShareGridClickHandle} 调用包含{@link IButtonClickDataCollect}参数的那个方法,进行处理
 * 5.对曝光事件进行处理
 */
public abstract class HandleDataCollectActivity extends BaseBackActivity implements IButtonClickDataCollect, IPageEventDataCollect {
    public ArticleItem articleItem = new ArticleItem();
    public boolean needSendNEWSAD = false;
    public boolean IS_NEWS_AD = false;
    protected boolean enableCollect = true;

   /* protected IPageBeatDataProvider iPageBeatDataProvider = new IPageBeatDataProvider() {
        @Override
        public Map<String, String> getPageBeatData() {
            return HQYDataCollectUtils.buildDataCollectParamsMap(articleItem);
        }

        @Override
        public String getPageName() {
            return HandleDataCollectActivity.this.getClass().getName();
        }
    };
*/

    /**
     * 弹出的那个评论框
     */
//    protected CommentPopupWindow commentDialogFram;
//    protected CommentPopupWindow commentDialogFram;
    protected void onPageStart() {
        collectPageStart();
    }

    protected long inTime;
    protected float scrollProp = (new SecureRandom().nextInt(6) + 5) / 10F;
    DecimalFormat decimalFormat = new DecimalFormat("#.##");

    public void setScrollProp(float value) {
        try {
            value = Float.parseFloat(decimalFormat.format(value));
            Log.w("Appfac", "setScrollProp value:" + value);
            if (value < scrollProp) return;
            if (value > 1F) {
                value = 1f;
            }
            scrollProp = value;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inTime = System.currentTimeMillis();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
//        commentDialogFram = new CommentPopupWindow(this);
//        commentDialogFram.setOnCommentListener(this);
        getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                sendNEWSAD();
                if (NavigateActivity.isOnPolicyInterpretation) {
                    int time = 1;
                    if (AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.integralConfig != null && AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.integralConfig.zhengce_least_duration_4 != 0) {
                        time = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.integralConfig.zhengce_least_duration_4;
                    }
                    AddIntegralCounter.start(HandleDataCollectActivity.this, new AddIntegralCounter.TimeoutCallback() {
                        @Override
                        public void timeoutCallback() {
                            if (articleItem == null) {
                                return;
                            }
                            //Log.e("tag","sssssssss 阅读政策");
                            Addintegral.addintegral(HandleDataCollectActivity.this, 55, articleItem);
                        }
                    }, time);

                }


            }
        });
    }

    public void sendNEWSAD() {
        try {

            if (getIntent() == null || !getIntent().hasExtra("needSendNEWSAD")) {
                return;
            }
            needSendNEWSAD = getIntent().getBooleanExtra("needSendNEWSAD", false);
            if (needSendNEWSAD || (articleItem != null && TypeX.NEWS.NEWS_AD == articleItem.getType())) {
                //分享公益活动：52
                //浏览公益宣传：54
                //阅读政策：55
                IS_NEWS_AD = true;

                int time = 1;
                if (AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.integralConfig != null && AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.integralConfig.gongyi_least_duration_4 != 0) {
                    time = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.integralConfig.gongyi_least_duration_4;
                }
                AddIntegralCounter.start(HandleDataCollectActivity.this, new AddIntegralCounter.TimeoutCallback() {
                    @Override
                    public void timeoutCallback() {
                        if (articleItem == null) {
                            return;
                        }
                        //Log.e("tag","sssssssss 浏览公益宣传");
                        Addintegral.addintegral(HandleDataCollectActivity.this, 54, articleItem);
                    }
                }, time);

            }
        } catch (Exception e) {

        }
    }


    @Override
    protected void onDestroy() {
        AudioFloatManager.Companion.getInstance(this).setOpenArticleId(0L);
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
        collectPageDestroy();
        TXReportManager.getInstance().clearThirdAndFourTabInfo();
    }

    @Override
    protected void onStart() {
        super.onStart();
        collectPageBeat();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopCollectPageBeat();
    }


    @Override
    protected void onResume() {
        super.onResume();
        collectPageBeat();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //由于整个app采用的是透明主题，开启下一个页面的时候不会调用onStop，因此在这里停止页面心跳
        stopCollectPageBeat();
    }

    @Override
    public void initButtonClick() {

    }

    @Override
    public void collectComment(@NonNull String content, String beReplayUserName, String beReplayUserId) {
        if (!enableCollect) {
            return;
        }
        UserInfo userInfo = UserInfo.getUserInfo(this);
        if (!userInfo.isLogin()) {
            Log.e(TAG, "user is not login why collect comment!");
            return;
        }
        DataCollectRequestButtonClickExpansion.operateComment(this.getClass().getName(), DataCollectRequestButtonClickExpansion.POSITIVE_ACTION, articleItem.getCatalogId() + "", articleItem.getId() + "", content, userInfo.getNickname(), beReplayUserName, userInfo.getUserid(), beReplayUserId);
    }

    @Override
    public void collectForward(String url, String destType, String catalogId, String articleId, String catalogName, String articleTitle) {
        if (!enableCollect) {
            return;
        }
        DataCollectRequestButtonClickExpansion.forward(this.getClass().getName(), url, destType, catalogId, articleId, catalogName, articleTitle);
    }

    @Override
    public void collectLike(boolean add, String catalogId, String articleId) {
        if (!enableCollect) {
            return;
        }
        UserInfo userInfo = UserInfo.getUserInfo(this);
        if (!userInfo.isLogin()) {
            Log.e(TAG, "user is not login why collect like !");
            return;
        }
        Log.w(TAG, "collect like praise");
        int operate = add ? DataCollectRequestButtonClickExpansion.POSITIVE_ACTION : DataCollectRequestButtonClickExpansion.NEGATIVE_ACTION;
        DataCollectRequestButtonClickExpansion.operateLike(this.getClass().getName(), operate, catalogId, articleId, userInfo.getNickname(), userInfo.getUserid());
    }

    @Override
    public void collectAttention(boolean add, String mediaId, String mediaName) {
        if (!enableCollect) {
            return;
        }
        UserInfo userInfo = UserInfo.getUserInfo(this);
        if (!userInfo.isLogin()) {
            Log.e(TAG, "user is not login why collect attention !");
            return;
        }
        int operate = add ? DataCollectRequestButtonClickExpansion.POSITIVE_ACTION : DataCollectRequestButtonClickExpansion.NEGATIVE_ACTION;
        DataCollectRequestButtonClickExpansion.operateMeidaAttention(this.getClass().getName(), mediaId, mediaName, operate, userInfo.getUserid(), userInfo.getNickname());
    }

    @Override
    public void collectPageStart() {
        if (!enableCollect) {
            return;
        }

    }

    @Override
    public void collectPageDestroy() {
        if (enableCollect) {

        }
    }

    @Override
    public void collectPageBeat() {
        if (enableCollect) {

        }
    }

    @Override
    public void stopCollectPageBeat() {
        if (enableCollect) {

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    private void commentCommitPush(CommentCommitPushEvent data) {
        collectComment(data.getContent(), data.getBeReplayUserName(), data.getBeReplayUserId());

    }
//    @Override
//    public void onComment(@NonNull String content, String beReplayUserName, String beReplayUserId) {
//        collectComment(content, beReplayUserName, beReplayUserId);
//        ReportManager.getInstance().submitComment(articleItem.getId()+"",articleItem.getTitle(),content);
//    }

    protected void sendExposureEvent() {
        TXReportManager.getInstance().app_jhapp_content_detail_imp(articleItem);
    }
}